package org.academic.texteditor.gui.plugin;

import javax.swing.JCheckBoxMenuItem;
import javax.swing.JMenu;
import javax.swing.KeyStroke;
import javax.swing.text.AttributeSet;

import org.academic.texteditor.gui.component.PageContainer;
import org.academic.texteditor.gui.component.PersonalizedTextPane;
import org.academic.texteditor.gui.component.menu.MenuFactory;
import org.academic.texteditor.gui.feature.Page;

public abstract class AbstractSelectionPlugin extends BasePlugin {

	private static final long serialVersionUID = -1568601382603127640L;

	protected PageContainer pageContainer;
	protected JCheckBoxMenuItem menuItem;
	
	public AbstractSelectionPlugin(String name) {
		super(name);
	}

	@Override
	public void initialize(PageContainer pageContainer) {
		this.pageContainer = pageContainer;
	}

	@Override
	public void activate() {
		JMenu menu = getParentMenu();
		menu.setVisible(true);
		
		menuItem = MenuFactory.createCheckBoxMenuItem(menu, -1, getMenuItemName(), getMenuItemKey(), this);
		
		KeyStroke keyStroke = getAcceleratorKey();
		if (keyStroke != null) {
			menuItem.setAccelerator(keyStroke);
		}
	}

	@Override
	public void execute() {
		boolean selected = menuItem.isSelected();
		
		Page page = pageContainer.getActualPage();
		PersonalizedTextPane textPane = page.getText().getTextPane();
		
		int selectionStart = textPane.getSelectionStart();
		int selectionEnd = textPane.getSelectionEnd();
		int length = selectionEnd - selectionStart;
		
		AttributeSet attributeSet;
		if (selected) {
			attributeSet = getOnAttributeSet();
		} else {
			attributeSet = getOffAttributeSet();
		}
		textPane.getStyledDocument().setCharacterAttributes(selectionStart, length, attributeSet, true);
	}

	@Override
	public void deactivate() {
		JMenu menu = getParentMenu();
		menu.setVisible(false);
		MenuFactory.removeMenuItem(menu, getMenuItemName());
	}

	@Override
	public void destroy() {

	}

	protected KeyStroke getAcceleratorKey() {
		return null;
	}
	
	protected abstract AttributeSet getOffAttributeSet();
	
	protected abstract AttributeSet getOnAttributeSet();
	
	protected abstract String getMenuItemKey();
	
	protected abstract String getMenuItemName();

	protected abstract JMenu getParentMenu();
	
}
